package client

import (
	"encoding/json"
	"findService/ss/servicebase"
	"jkgo/jk/jklog"
	"jkgo/jkdbs"
	"time"
)

type ClientMqtt struct {
	c *servicebase.SSIoTClient
	servicebase.MsgHandle
	db *jkdbs.Mongo
}

func ClientMqttNew(addr string, port int, id string, db *jkdbs.Mongo) (*ClientMqtt, error) {
	cm := &ClientMqtt{}
	cm.db = db
	cm.c, _ = servicebase.NewSSIoTClient(addr, port, id)
	cm.c.SetMsgHandle(cm)
	go cm.c.Connect()
	return cm, nil
}

func (c *ClientMqtt) IoTDealMessage(topic, msg string) error {
	jklog.L().Infoln("topic ", topic, ",msg ", msg)
	if topic == "/report" {
		cl, err := STClientNew(c.db)
		if err != nil {
			return err
		}
		var up UploadDataInfo
		err = json.Unmarshal([]byte(msg), &up)
		if err != nil {
			return err
		}
		up.UploadTime = time.Now().Unix()
		d, err := json.Marshal(&up)
		if err != nil {
			return err
		}
		jklog.L().Infoln("save len ", len(d))
		jklog.L().Debugln("save data ", string(d))
		err = cl.SaveData(string(d))
		return err
	}
	return nil
}

func (c *ClientMqtt) IoTStatusReport(status string) {
	jklog.L().Infoln("status: ", status)
	if status == "connected" {
		c.c.Sub("/report")
	}
}

func (c *ClientMqtt) Close() {
	c.c.Close()
}
